<?php
/*
 module:		发布管理
 create_time:	2022-04-07 19:34:18
 author:		
 contact:		
*/

namespace app\backend\controller;

use app\api\model\ZhAuthParent;
use app\api\service\ZhBalanceService;
use app\backend\model\Member as MemberModel;
use app\backend\model\SysSite as SysSiteModel;
use app\backend\model\ZhMatchmaker as ZhMatchmakerModel;
use app\backend\service\ExportService;
use app\backend\service\ZhAuthenticationService;
use app\backend\model\ZhAuthentication as ZhAuthenticationModel;
use think\db\Where;
use think\facade\App;
use think\facade\Db;
use app\backend\model\ZhMatchmaker;
use app\backend\model\Member;
use think\facade\Filesystem;


class ZhAuthentication extends Admin
{
    function selectList()
    {
        $authentication_id = $this->request->get('authentication_id');
        $this->view->assign('authentication_id', $authentication_id);
        return view('select_list');
    }

    /*首页数据列表*/
    function index()
    {
        if (!$this->request->isAjax()) {
            return view('index');
        } else {
            $limit   = $this->request->post('limit', 20, 'intval');
            $offset  = $this->request->post('offset', 0, 'intval');
            $page    = floor($offset / $limit) + 1;
            $keyword = $this->request->param('keyword', '', 'serach_in');
            $where = [];
            $where['a.simple_name']    = ['like', $this->request->param('simple_name', '', 'serach_in')];
            $where['a.gender']         = $this->request->param('gender', '', 'serach_in');
            $where['a.date_birth']     = ['like', $this->request->param('date_birth', '', 'serach_in')];
            $where['a.city']           = ['like', $this->request->param('city', '', 'serach_in')];
            $where['a.marital_status'] = $this->request->param('marital_status', '', 'serach_in');
            $where['a.income']         = ['like', $this->request->param('income', '', 'serach_in')];
            $where['a.release_type']   = $this->request->param('release_type', '', 'serach_in');
            $order                     = $this->request->post('order', '', 'serach_in');    //排序字段 bootstrap-table 传入
            $sort                      = $this->request->post('sort', '', 'serach_in');        //排序方式 desc 或 asc
            $field   = 'm.name,a.notes,a.authentication_id,a.head_portrait,a.simple_name,a.gender,a.age,a.date_birth,a.city,a.contact,a.release_type,a.status,a.is_frame,a.matchmaker_id';
            $orderby = ($sort && $order) ? $sort . ' ' . $order : 'a.authentication_id desc ';
            if ($keyword != '') {
                $where2 = "    a.purchase_status like '%{$keyword}%' or a.vehicle_status like '%{$keyword}%'
                        or a.tags like '%{$keyword}%' or a.occupation like '%{$keyword}%'
                        or a.real_name like  '%$keyword%'  or a.gender like '%{$keyword}%'
                        or a.education like '%{$keyword}%' or a.marital_status like '%{$keyword}%'  or a.city like '%{$keyword}%'
                        or a.county like '%{$keyword}%' or a.income  like '%{$keyword}%'
                        or a.age like '%{$keyword}%'  or a.height like '%{$keyword}%' or a.animal like '%{$keyword}%'
                        or a.have_children  like '%{$keyword} %' or  a.belief like '%{$keyword} %' or notes like '%{$keyword}%'
                        or a.mbti  like '%{$keyword} %' or a.lova_declaration like '%{$keyword} %' or a.real_name like '%{$keyword}%'
                        or a.contact like '%{$keyword}%' or a.nation like  '%{$keyword} %' or a.family_status  like '%{$keyword}%'
                        or a.appearance   like '%{$keyword}%' or a.commitment  like '%{$keyword}%' or a.work like '%{$keyword}%'
                        or a.simple_name  like '%{$keyword}%'  or a.other_describe like '%{$keyword}%'
                           
                        ";
                $res    = ZhAuthenticationModel::alias('a')->leftJoin('zh_matchmaker m', 'a.matchmaker_id=m.matchmaker_id')->where($where2)->field($field)->order("a.authentication_id desc ")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
                $res    = ['rows' => $res['data'], 'total' => $res['total']];
            } else {
                $res = ZhAuthenticationService::indexList(formatWhere($where), $field, $orderby, $limit, $page);
            }
            foreach ($res['rows'] as &$v) {
                if ($v['matchmaker_id']) {
                    $matchmakerData = ZhMatchmakerModel::where([
                        'u_id'     => $v['matchmaker_id'],
                        'wxapp_id' => session('backend.wxapp_id')
                    ])->find();
                    if ($matchmakerData) {
                        $v['matchmaker_name'] = $matchmakerData['is_personal'] == '1' ? $matchmakerData['name'] : $matchmakerData['organization_name'];
                    }
                } else {
                    $v['matchmaker_name'] = '';
                }
            }
            unset($v);
            return json($res);
        }
    }

    /*修改排序开关按钮操作*/
    function updateExt()
    {
        $postField = 'authentication_id,is_frame';
        $data      = $this->request->only(explode(',', $postField), 'post', null);
        if (!$data['authentication_id']) $this->error('参数错误');
        try {
            ZhAuthenticationModel::update($data);
        } catch (\Exception $e) {
            abort(config('my.error_log_code'), $e->getMessage());
        }
        return json(['status' => '00', 'msg' => '操作成功']);
    }

    /*删除*/
    function delete()
    {
        $idx = $this->request->post('authentication_id', '', 'serach_in');
        if (!$idx) $this->error('参数错误');
        try {
            ZhAuthenticationModel::destroy(['authentication_id' => explode(',', $idx)], true);
        } catch (\Exception $e) {
            abort(config('my.error_log_code'), $e->getMessage());
        }
        return json(['status' => '00', 'msg' => '操作成功']);
    }

    /*查看详情*/
    function view()
    {
        $authentication_id = $this->request->get('authentication_id', '', 'serach_in');
        if (!$authentication_id) $this->error('参数错误');

        $sql = 'select a.*,b.name,b.phone,b.organization_name,b.is_personal,m.phone as u_id_name from gc_zh_authentication as a 
                left join gc_zh_matchmaker as b on a.matchmaker_id = b.matchmaker_id
                left join gc_member as m on a.u_id=m.uid
                where a.authentication_id = ' . $authentication_id . ' limit 1';

        //$sql = 'select a.*,b.name,b.phone,b.organization_name,b.is_personal from gc_zh_authentication as a left join gc_zh_matchmaker as b on a.matchmaker_id = b.u_id where a.authentication_id = '.$authentication_id.' limit 1';
        $info                   = Db::connect('mysql')->query($sql);
        $info['photos']         = json_decode(htmlspecialchars_decode($info[0]['photos']), true);
        $info['videos']         = json_decode(htmlspecialchars_decode($info[0]['videos']), true);
        $info[0]["o_education"] = explode(',', $info[0]["o_education"]);
        $o_edu_str              = "";
        foreach ($info[0]["o_education"] as $o_val) {
            switch ($o_val) {
                case "0":
                    $o_edu_str .= " 不限";
                    break;
                case "1":
                    $o_edu_str .= " 小学";
                    break;
                case "2":
                    $o_edu_str .= " 初中";
                    break;
                case "3":
                    $o_edu_str .= " 高中";
                    break;
                case "4":
                    $o_edu_str .= " 大专";
                    break;
                case "5":
                    $o_edu_str .= " 专升本";
                    break;
                case "6":
                    $o_edu_str .= " 本科";
                    break;
                case "7":
                    $o_edu_str .= " 硕士";
                    break;
                case "8":
                    $o_edu_str .= " 博士";
                    break;
                case "9":
                    $o_edu_str .= " 海归留学";
                    break;
                case "10":
                    $o_edu_str .= " 中专/高职";
                /*     default:
                         $info["education"]="其他";
                         break;*/
            }
        }
        $info[0]["o_education"] = $o_edu_str;
        switch ($info[0]["education"]) {
            case "0":
                $info[0]["education"] = "保密";
                break;
            case "1":
                $info[0]["education"] = "小学";
                break;
            case "2":
                $info[0]["education"] = "初中";
                break;
            case "3":
                $info[0]["education"] = "高中";
                break;
            case "4":
                $info[0]["education"] = "大专";
                break;
            case "5":
                $info[0]["education"] = "专升本";
                break;
            case "6":
                $info[0]["education"] = "本科";
                break;
            case "7":
                $info[0]["education"] = "硕士";
                break;
            case "8":
                $info[0]["education"] = "博士";
                break;
            case "9":
                $info[0]["education"] = "海归留学";
                break;
            case "10":
                $info[0]["education"] = "中专/高职";
                break;
            /*     default:
                     $info["education"]="其他";
                     break;*/
        }
        /*  $info["o_marital_status"]=explode(",", $info["o_marital_status"]);*/
        $this->view->assign('info', current($info));
        // print_r(  explode(',',$info["photos"]));exit();
        $p_li = "";
        foreach ($info['photos'] as $vo) {
            $p_li .= ' <li style="float:left; margin-bottom:2px; margin-right:2px;">';
            $p_li .= '<a href="javascript:void(0)" onclick="openImg(' . $vo;
            $p_li .= ')"><img height="60" src="' . $vo;
            $p_li .= '"  ></a></li>';
        }
        $this->view->assign('p_li', $p_li);
        return view('view');
    }


    /*修改*/
    function update()
    {
        if (!$this->request->isPost()) {

            $authentication_id = $this->request->get('authentication_id', '', 'serach_in');
            if (!$authentication_id) $this->error('参数错误');
            $sql  = 'select a.*,b.name,b.phone,b.organization_name,b.is_personal,m.phone as u_id_name from gc_zh_authentication as a 
                left join gc_zh_matchmaker as b on a.matchmaker_id = b.matchmaker_id
                left join gc_member as m on a.u_id=m.uid
                where a.authentication_id = ' . $authentication_id . ' limit 1';
            $info = Db::connect('mysql')->query($sql);
            if (is_array($info) && count($info) > 0) {
                $info = $info[0];
            }
            $info['photos'] = htmlspecialchars_decode($info['photos']);
            if (empty($info['photos']) || $info['photos'] == 'null') {
                $info['photos'] = '[]';
            }
            $info['videos'] = htmlspecialchars_decode($info['videos']);
            if (empty($info['videos']) || $info['videos'] == 'null') {
                $info['videos'] = '[]';
            }
            $info["o_education"]      = explode(',', $info["o_education"]);
            $info["o_marital_status"] = explode(",", $info["o_marital_status"]);

            $this->view->assign('info', checkData($info));
            return view('update');
        } else {
            //2024.3.22新增：simple_name,is_party_member字段，详情说明见数据库
            //2024.5.11新增：mbti，constellation，tags字段，详情说明见数据库
            $postField = 'address,province,city,county,photo_auth,other_describe,o_child,o_max_height,o_min_height,o_max_age,o_min_age,o_jg,work,self_built,notes,a.age,u_id,animal,appearance,belief,contacts,commitment,zodiac_clash,sibling,parental_status,authentication_id,head_portrait,real_name,gender,date_birth,height,weight,education,marital_status,have_children,contact_type,contact,nation,occupation,photos,videos,income,purchase_status,vehicle_status,is_smoking,is_drink,lova_declaration,o_age,o_height,o_county,o_weight,o_education,o_marital_status,o_income,o_nation,o_purchase_status,o_vehicle_status,o_is_smoking,o_is_drink,o_remarks,is_top,status,simple_name,is_party_member,mbti,constellation,tags,age,o_max_weight,o_min_weight,o_other,job';
            // o_min_age  o_max_age  o_age o_min_height  o_max_height o_weight o_min_weight  o_max_weight
            $data                     = $this->request->only(explode(',', $postField), 'post', null);
            $data["o_education"]      = implode(",", $data["o_education"]);
            $data["o_marital_status"] = implode(",", $data["o_marital_status"]);
            $u_id                     = intval($data["u_id"]);
            //去掉已被绑定的佳人
            if ($u_id > 0) {
                $zhauthentication = new ZhAuthenticationModel();
                $res              = $zhauthentication->where("u_id", $u_id)->save(["u_id" => 0]);
            }
            $data['updatetime'] = time();
            $res = ZhAuthenticationService::update($data);
            //审核通过，查看当前红娘等级是否达到升级，达到则自动升级
            $status = $this->request->post("status");
            if ($status == 1) {
                $id               = $this->request->post("authentication_id");
                $zhauthentication = ZhAuthenticationModel::where(["authentication_id" => $id])->find();
                //不是所有资料都有红娘
                if ($zhauthentication["matchmaker_id"] > 0) {
                    $matchmaker       = ZhMatchmakerModel::where(["matchmaker_id" => $zhauthentication["matchmaker_id"]])->find();
                    $matchmaker_level = $matchmaker["level_id"];
                    //26 普通红娘 8专属红娘 9金牌红娘 10钻石红娘
                    //$level_info = \app\backend\model\ZhMatchmakerLevel::where(["id" => $matchmaker_level])->find();
                    if ($matchmaker_level == 26) {
                        $next_level   = \app\backend\model\ZhMatchmakerLevel::where(["id" => 8])->find();
                        $nex_level_id = 8;
                    } elseif ($matchmaker_level == 8) {
                        $next_level   = \app\backend\model\ZhMatchmakerLevel::where(["id" => 9])->find();
                        $nex_level_id = 9;
                    } elseif ($matchmaker_level == 9) {
                        $next_level   = \app\backend\model\ZhMatchmakerLevel::where(["id" => 10])->find();
                        $nex_level_id = 10;
                    }
                    if ($next_level) {
                        //下一等级所需数量
                        $next_num = $next_level["up_num"];
                        //当前的数量
                        $z_up_num = ZhAuthenticationModel::where(["matchmaker_id" => $zhauthentication["matchmaker_id"], "status" => 1])->count();
                        if ($z_up_num >= $next_num) {
                            $m_data["matchmaker_id"] = $zhauthentication["matchmaker_id"];
                            $m_data["level_id"]      = $nex_level_id;
                            $result                  = ZhMatchmakerModel::update($m_data);
                        }
                    }

                    $wxappId = session('backend.wxapp_id');
                    //如果资料有效，增加奖励
                    $sysInfo = SysSiteModel::where(['wxapp_id' => $wxappId])->field('id, wxapp_id, valid_profile')->find()->toArray();
                    //如果资料
                    if ($sysInfo['valid_profile'] > 0) {
                        //更新红娘的奖励 类型：上传有效的佳人资料
                        ZhBalanceService::updateMoneyBalanceLog($wxappId, $matchmaker['u_id'], $sysInfo['valid_profile'], "收入", "上传有效的佳人资料", "");
                        //Member::where(['uid' => $matchmaker['u_id']])->update(['balance' => Db::raw('balance+' . $sysInfo['valid_profile'])]);
                    }

                    //如果没有参与过推广计算  审核通过资料数大于10 上级邀请红娘余额+2
                    if ($matchmaker['flag'] == 0) {
                        $z_num = ZhAuthenticationModel::where(["matchmaker_id" => $zhauthentication["matchmaker_id"], "status" => 1])->count();
                        if ($z_num >= 10) {
                            //查找上级红娘信息
                            if ($matchmaker['top_matchmaker_id']) {
                                $top_matchmaker = ZhMatchmakerModel::where(["matchmaker_id" => $matchmaker['top_matchmaker_id']])->find();
                                //上级红娘用户表存在
                                if ($top_matchmaker['u_id']) {
                                    $res = ZhBalanceService::updateMoneyBalanceLog($wxappId, $top_matchmaker['u_id'], 2, "收入", "推荐有效红娘","");
                                    //$res = Member::where(['uid' => $top_matchmaker['u_id']])->update(['balance' => Db::raw('balance+2')]);
                                    if ($res) {//标记该红娘已经参加过推广活动
                                        ZhMatchmakerModel::where(["matchmaker_id" => $zhauthentication["matchmaker_id"]])->update(['flag' => 1]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return json(['status' => '00', 'msg' => '修改成功']);
        }
    }

    /*添加*/
    function add()
    {
        if (!$this->request->isPost()) {
            return view('add');
        } else {
            //2024.3.22新增：simple_name,is_party_member字段，详情说明见数据库
            //2024.5.11新增：mbti，constellation，tags字段，详情说明见数据库
            $postField = 'address,province,city,county,photo_auth,other_describe,o_child,o_max_height,o_min_height,o_max_age,o_min_age,o_jg,work,self_built,notes,a.age,u_id,animal,appearance,belief,contacts,commitment,zodiac_clash,sibling,parental_status,authentication_id,head_portrait,real_name,gender,date_birth,height,weight,education,marital_status,have_children,contact_type,contact,nation,occupation,photos,videos,income,purchase_status,vehicle_status,is_smoking,is_drink,lova_declaration,o_age,o_height,o_county,o_weight,o_education,o_marital_status,o_income,o_nation,o_purchase_status,o_vehicle_status,o_is_smoking,o_is_drink,o_remarks,is_top,status,simple_name,is_party_member,mbti,constellation,tags,age,o_max_weight,o_min_weight,o_other,job';
            // o_min_age  o_max_age  o_age o_min_height  o_max_height o_weight o_min_weight  o_max_weight
            $data                     = $this->request->only(explode(',', $postField), 'post', null);
            $data["o_education"]      = implode(",", $data["o_education"]);
            $data["o_marital_status"] = implode(",", $data["o_marital_status"]);
            $u_id                     = intval($data["u_id"]);
            //去掉已被绑定的佳人
            if ($u_id > 0) {
                $zhauthentication = new ZhAuthenticationModel();
                $res              = $zhauthentication->where("u_id", $u_id)->save(["u_id" => 0]);
            }
            $data['updatetime'] = time();
            $res = ZhAuthenticationService::add($data);
            return json(['status' => '00', 'msg' => '添加成功']);
        }
    }
    function import()
    {
        $file           = $this->request->file("file");
        $save_name      = Filesystem::disk('public')->putFile('file/xls', $file);
        $data           = baseFromExcel('/' . App::getRootPath() . 'public/uploads/' . $save_name);
        $filedData2     = [
            '真实姓名'       => 'real_name',
            '昵称'           => 'simple_name',
            '性别'           => 'gender',
            '出生日期'       => 'date_birth',
            '年龄（虚岁）'     => 'age',
            '城市'           => 'city',
            '省份'           => 'province',
            '街道'           => 'county',
            '区'           => 'county',
            '所在地'         => 'address',
            '身高（cm）'       => 'height',
            '爱情宣言'       => 'lova_declaration',
            '联系方式'       => 'contact_type',
            '手机号'         => 'contact',
            '体重（斤）'       => 'weight',
            '学历'           => 'education',
            '婚姻状况'       => 'marital_status',
            '有无子女'       => 'have_children',
            '民族'           => 'nation',
            '职业'           => 'occupation',
            '家庭情况'       => 'family_status',
            '购房情况'       => 'purchase_status',
            '自建房'         => 'self_built',
            '父母情况'       => 'parental_status',
            '购车情况'       => 'vehicle_status',
            '是否吸烟'       => 'is_smoking',
            '是否喝酒'       => 'is_drink',
            '所属红娘手机号' => 'matchmaker_id', // 需要将手机号转成id
            '属相'           => 'animal',
            '品貌'           => 'appearance',
            '信仰'           => 'belief',
            '有无自建房'     => 'self_built',
            '年薪（万）'       => 'income',
            '父母状况'       => 'parental_status',
            '兄弟姐妹'       => 'sibling',
            '属相（冲）（宜）'   => 'zodiac_clash',
            '承诺'           => 'commitment',
            '联系人'         => 'contact',
            '联系人电话'     => 'contacts',
            'MBTI'           => 'mbti',
            '星座'           => 'constellation',
            '资料标签'       => 'tags',
            '红娘备注'       => 'notes',
            '是否党员'       => 'is_party_member',
            '工作单位'       => 'work',
            '征婚宣言'       => 'lova_declaration',
            '择偶籍贯'       => 'o_jg',
            '择偶最小年龄'   => 'o_min_age', '择偶最大年龄' => 'o_max_age', '择偶年龄' => 'o_age', '择偶身高' => 'o_height',
            '择偶所在地'     => 'o_city', '择偶体重' => 'o_weight', '择偶学历' => 'o_education',
            '择偶婚况'       => 'o_marital_status', '择偶年薪' => 'o_income',
            '择偶购房情况'   => 'o_purchase_status', '择偶购车情况' => 'o_vehicle_status',
            '择偶是否吸烟'   => 'o_is_smoking', '择偶是否喝酒' => 'o_is_drink',
            '择偶最小身高'   => 'o_min_height', '择偶最大身高' => 'o_max_height',
            '择偶最小体重'   => 'o_min_weight', '择偶最大体重' => 'o_max_weight',
            '择偶婚姻状况'   => 'o_marital_status', '择偶有无小孩' => 'o_child', '择偶要求描述' => 'o_other',
            '择偶年收入'=>'o_income',

            '择偶民族'       => 'o_nation', '你的理想型' => 'o_remarks', '是否家长' => 'is_parent', '佳人其他情况描述' => 'other_describe'
        ];
        $marital_status = [
            '未婚' => 1,
            '离异' => 2,
            '丧偶' => 3,
            '短婚' => 4
        ];
        $have_children  = [
            '无'   => 2,
            '没有' => 2,
            '有'   => 1,
        ];
        $self_built     = [
            '有'       => 1,
            '没有'     => 2,
            '自建别墅' => 3
        ];
        $education_val  = [
            '保密'      => 0,
            '小学'      => 1,
            '初中'      => 2,
            '中专/高职' => 10,
            '高中'      => 3,
            '大专'      => 4,
            '专升本'    => 5,
            '本科'      => 6,
            '硕士'      => 7,
            '博士'      => 8,
            '海归留学'  => 9,
        ];
        $gender         = [
            '男' => 1,
            '女' => 2,
        ];
        $purchase_status = [
            '无房'       => 1,
            '一套'       => 2,
            '一套房'       => 2,
            '两套'       => 3,
            '两套房'       => 3,
            '三套及以上' => 4,
            '三套以上'   => 4,
            '三套'       => 4,
            '婚后买房'   => 5,
            '拆迁分房'   => 6,
            '别墅/排屋'  => 7
        ];
        $vehicle_status  = [
            '多辆车' => 3,
            '一辆车' => 2,
            '未购车' => 1,
            '不限'=>0
        ];
        $is              = [
            '是' => 1,
            '否' => 2,
        ];

        $o_income_val=[
            '不限'       => 0,
            '10-15万'       => 2,
            '16-20万'       => 3,
            '20万-50万' => 4,
            '50万-100万'   => 5,

            '100万以上'   => 6];
        $o_education_val=[
            '不限'=>0,
            '小学'=>1,
            '初中'=>2,
            '中专/高职'=>10,
            '高中'=>3,
            '大专'=>4,
            '专升本'=>5,
            '本科'=>6,
            '硕士'=>7,
            '博士'=>8,
            '海归留学'=>9,
        ];
        $o_child = [
            '不限'=>0,
            '有'=>1,
            '无'=>2
        ];
        $newData_p       = [];
        $newData2        = [];
        $exist           = [];
        $data = array_filter($data, function($row) {
            // 如果这行数据不全是 null，返回 true，保留该行
            return count(array_filter($row, function($value) {
                    return !is_null($value) && trim($value) !== '';
                })) > 0;
        });

        foreach ($data as $row) {
            $newRow2 = [];
            /**
             * $row 的格式
             * Array
             * (
             * [昵称] => 测试昵称1
             * [余额] => 1
             * [真实姓名] => 张三
             * [手机号] => 15261304594
             * [出生日期] => 34322
             * [身高] => 167
             * [性别] => 男
             * [爱情宣言] => 相貌好
             * [标签] => 高富帅,有钱
             * [所在地城市] => 天津市
             * [体重] => 50
             * [学历] => 硕士研究生
             * [婚姻状况] => 未婚
             * [有无子女] => 没有
             * [民族] => 汉族
             * [职业] => 设计师
             * [家庭情况] => 父母弟弟
             * [月收入] => 8000
             * [购房情况] => 已购房
             * [购车情况] => 未购车
             * [是否抽烟] => 否
             * [是否喝酒] => 否
             * [择偶年龄] => 25,30
             * [择偶身高] => 160175
             * [择偶所在地] => 天津市
             * [择偶体重] => 50,70
             * [择偶学历] => 本科
             * [择偶婚况] => 未婚
             * [择偶月收入] => 8001-12000
             * [择偶民族] => 汉族
             * [择偶购房情况] => 已购房
             * [择偶购车情况] => 未购车
             * [择偶是否吸烟] => 否
             * [择偶是否喝酒] => 否
             * [我的理想型] => 活泼开朗
             * [所属红娘手机号] => 15934485623
             * [属相] =>
             * [品貌] =>
             * [信仰] =>
             * [年薪] =>
             * [父母状况] =>
             * [兄弟姐妹] =>
             * [属相冲] =>
             * [承诺] =>
             * [联系人] =>
             * [MBTI] => 测试
             * [星座] => 双子座
             * [资料标签] => 高净值,经商
             * )
             */
            foreach ($row as $key => $datum) {
                if ($this->in_data_array($key, $filedData2)) {
                    $newRow2[$filedData2[$key]] = $datum === null ? '' : $datum;
                }
            }

            // 红娘信息
            if ($newRow2['matchmaker_id']) {
                $matchmakerInfo = ZhMatchmakerModel::where('phone', $newRow2['matchmaker_id'])->find();
                if ($matchmakerInfo) {
                    $newRow2['matchmaker_id'] = $matchmakerInfo->matchmaker_id;
                } else {
                    $newRow2['matchmaker_id'] = 0;
                }
            } else {
                $newRow2['matchmaker_id'] = 0;
            }
            //非空验证开始
            $check_res = $this->check_emp($newRow2);
            if ($check_res) {
                return json(['status' => '00', 'msg' => 'null break..', 'exist' => $check_res]);
                continue;
            }
            $newRow2['u_id'] = 0;
            // 查找资料有没有
            if ($newRow2['u_id']) {
                $authInfo = \app\backend\model\ZhAuthentication::where('u_id', $newRow2['u_id'])->find();
                if ($authInfo) {
                    $exist[] = $authInfo['authentication_id'];
                    continue;
                }
            }
            $newRow2['contact_type']      = '电话';
            $newRow2['gender']            = $gender[$newRow2['gender']];
            $newRow2['marital_status']    = $marital_status[$newRow2['marital_status']];
            $newRow2['education']         = $education_val[$newRow2['education']];
            $newRow2['have_children']     = $have_children[$newRow2['have_children']];
            $newRow2['purchase_status']   = intval($purchase_status[$newRow2['purchase_status']]);
            $newRow2['vehicle_status']    = intval($vehicle_status[$newRow2['vehicle_status']]);
//            $newRow2['self_built']        = $is[$newRow2['u']] ?? 0;
            $newRow2['is_smoking']        = $is[$newRow2['is_smoking']] ?? 0;
            $newRow2['is_drink']          = $is[$newRow2['is_drink']] ?? 0;
            $newRow2['o_marital_status']  = $marital_status[$newRow2['o_marital_status']] ?? 0;
            $newRow2['o_purchase_status'] = $purchase_status[$newRow2['o_purchase_status']] ?? 0;
            $newRow2['o_vehicle_status']  = $vehicle_status[$newRow2['o_vehicle_status']] ?? 0;
            $newRow2['self_built']        = $self_built[$newRow2['self_built']] ?? 0;
            $newRow2['o_is_smoking']      = $is[$newRow2['o_is_smoking']] ?? 0;
            $newRow2['o_is_drink']        = $is[$newRow2['o_is_drink']] ?? 0;
            $newRow2['o_income']  = $o_income_val[$newRow2['o_income']] ?? 0;
            $newRow2['o_education']  = $o_education_val[$newRow2['o_education']] ?? 0;
            $newRow2['createtime']        = time();
            $time                         = intval(($newRow2['date_birth'] - 25569) * 3600 * 24); //转换成1970年以来的秒数
            $newRow2['date_birth']        = gmdate('Y-m-d', $time);
            $newRow2['wxapp_id']          = session('backend.wxapp_id');
            //审核状态，默认待审核
            $newRow2['status']=0;
            //置顶状态 默认不置顶
            $newRow2['is_top'] = 0;
            //择偶有无小孩
            $newRow2['o_child']     = $o_child[$newRow2['o_child']]??0;
            $newData2[]=$newRow2;
        }

        $result=ZhAuthenticationModel::insertAll($newData2);
        $sql=ZhAuthenticationModel::getLastsql();
        return json(['status' => '00', 'msg' => '操作成功', 'exist' => $exist,'data'=>$newRow2,'res'=>$result,'sql'=>$sql]);
    }


    //导入用户，验证字段是否存在空，存在的话返回true
    function check_emp($newRow2)
    {

        /*   if(trim($newRow2['age'])==""||trim($newRow2['age'])==" "){
               return "age";
           }
           if(trim($newRow2['marital_status'])==""||trim($newRow2['marital_status'])==" "){
               return "marital_status";
           }*/
        /*if(trim($newRow2['city'])==""||trim($newRow2['city'])==" "){
            return "city";
        }*/
        /*       if(trim($newRow2['animal'])==""||trim($newRow2['animal'])==" "){
                   return "animal";
               }
               if(trim($newRow2['gender'])==""||trim($newRow2['gender'])==" "){
                   return "gender";
               }
               if(trim($newRow2['height'])==""||trim($newRow2['height'])==" "){
                   return "height";
               }
               if(trim($newRow2['weight'])==""||trim($newRow2['weight'])==" "){
                   return "weight";
               }
               if(trim($newRow2['education'])==""||trim($newRow2['education'])==" "){
                   return "education";
               }

               if(trim($newRow2['occupation'])==""||trim($newRow2['occupation'])==" "){

                   return "occupation";
               }
               if(trim($newRow2['appearance'])==""||trim($newRow2['appearance'])==" "){
                   return "appearance";
               }
               if(trim($newRow2['income'])==""||trim($newRow2['income'])==" "){
                   return "income";
               }
               if(trim($newRow2['purchase_status'])==""||trim($newRow2['purchase_status'])==" "){
                   return "purchase_status";
               }*/
        /*  if(trim($newRow2['have_children'])==""||trim($newRow2['have_children'])==" "){
              return "have_children";
          }*/
        /*  if(trim($newRow2['sibling'])==""||trim($newRow2['sibling'])==" "){
              return "sibling";
          }*/
        /* if(trim($newRow2['zodiac_clash'])==""||trim($newRow2['zodiac_clash'])==" "){
             return "zodiac_clash";
         }*/
        return false;
    }

    function in_data_array($key, $array)
    {
        foreach ($array as $k => $item) {
            if ($k == $key) {
                return true;
            }
        }
        return false;
    }

    // 导出
    public function export()
    {
        $nobuildfields = ['authentication_id','real_name', 'county', 'address', 'animal', 'gender',
            'height', 'weight','education', 'occupation','appearance','belief','income',
            'purchase_status','self_built','vehicle_status','parental_status','sibling','zodiac_clash',
            'have_children','other_describe','notes' ];
        $education_str=["0"=>"保密","1"=>"小学","2"=>"初中","3"=>"高中","4"=>"大专","5"=>"专升本","6"=>"本科","7"=>"硕士",
            "8"=>"博士","9"=>"海归留学","10"=>"中专/高职"];
        $gender_str=["1"=>"男","2"=>"女"];
        $self_built_str=["1"=>"有","2"=>"没有","3"=>"自建别墅"];
        $purchase_status_str=["1"=>"无房","2"=>"一套","3"=>"两套","4"=>"三套及以上","5"=>"婚后买房","6"=>"拆迁分房","7"=>"别墅/排屋"];
        $vehicle_status_str=["1"=>"一辆车","2"=>"多辆车","0"=>"未购车"];
        $expCellName = [
            'authentication_id' => 'Id',
            'real_name' => '真实姓名',
            'mname'=>'上级红娘',
            'county'             => '区',
            'address'            => '详细地址',
            'animal'          => '属相',
            'gender'        => '性别',
            'height'         => '身高',
            'weight'        => '体重',
            'education'        => '学历',
            'occupation'           => '职业',
            'appearance'           => '品貌',
            'belief'         => '信仰',
            'income'         => '年薪',
            'purchase_status'              => '购房情况',
            'self_built'            => '有无自建房',
            'vehicle_status'         => '购车情况',
            'parental_status'              => '父母状况',
            'sibling'            => '兄弟姐妹',
            'zodiac_clash'=>'属相(冲)(宜)',
            'have_children'=>'有无子女',
            'other_describe'=>'佳人其他情况描述',
            'notes'=>'红娘备注',
            ];
        $export      = new ExportService();
        $spreadsheet = null;
        $sheet       = null;
        $limit   = 10000;
        $offset  = 0;
        $page    = floor($offset / $limit) + 1;
        $res = ZhAuthenticationModel::alias('a')->leftJoin('zh_matchmaker m', 'a.matchmaker_id=m.matchmaker_id')
            ->field(["a.authentication_id"])->order("a.authentication_id desc ")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();

        $total=$res["total"];

        if ($total == 0) {
            $this->error('导出数据为空');
        }
        $current_total = 0;     // 当前已循环条数
        $page_size     = 10000;
        $total_page    = intval(ceil($total / $page_size));

        for ($i = 0; $i < $total_page; $i++) {
            $page         = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;
            $res = ZhAuthenticationModel::alias('a')->leftJoin('zh_matchmaker m', 'a.matchmaker_id=m.matchmaker_id')
            ->field(["m.name as mname","a.*"])->order("a.authentication_id desc ")->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
            $list=$res["data"];
             foreach ($list as $key => &$val) {
                 $val['gender']=$gender_str[$val['gender']];
                $val['education']=$education_str[$val['education']];
                $val['self_built']=$self_built_str[$val['self_built']];
                $val['purchase_status']=$purchase_status_str[$val['purchase_status']];
                $val['vehicle_status']=$vehicle_status_str[$val['vehicle_status']];
            }
            $current_total += count($list);     // 当前循环总条数
            $export->exportExcel('佳人数据-' . date('Y-m-d H:i:s'), $expCellName, $list, $spreadsheet, $sheet, [
                'page'          => $page,
                'page_size'     => 50000,      // 如果传了 current_total 则 page_size 就不用了
                'current_total' => $current_total,      // page_size 是 order 的，但是 newList 其实是 order_item 的
                'is_last_page'  => $is_last_page
            ]);
        }
    }

}

